package com.smartfactory.sail.controller;


import com.ada.base.common.ApiResponse;
import com.ada.base.common.ControllerResponse;
import com.smartfactory.sail.config.OperRecord;
import com.smartfactory.sail.entity.ItemWorkingprocedureDevice;
import com.smartfactory.sail.service.IDeviceService;
import com.smartfactory.sail.service.IItemWorkingprocedureDeviceService;
import com.smartfactory.sail.utils.StringUtils;
import com.smartfactory.sail.vo.device.ItemWorkingprocedureDeviceReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 产品工序设备 前端控制器
 * </p>
 *
 * @author 王巨壁
 * @since 2019-08-13
 */
@Api(tags = "产品工序设备")
@RestController
@RequestMapping("/item-workingprocedure-device")
public class ItemWorkingprocedureDeviceController extends ControllerResponse {
    private IItemWorkingprocedureDeviceService iItemWorkingprocedureDeviceService;
    private IDeviceService iDeviceService;

    public ItemWorkingprocedureDeviceController(IItemWorkingprocedureDeviceService iItemWorkingprocedureDeviceService, IDeviceService iDeviceService) {
        this.iItemWorkingprocedureDeviceService = iItemWorkingprocedureDeviceService;
        this.iDeviceService = iDeviceService;
    }

    @OperRecord(content = "分配生产设备",level = 1)
    @PostMapping
    @ApiOperation(value = "新增产品工序设备", notes = "新增产品工序设备")
    public ApiResponse<Object> saveBatch(@RequestBody List<ItemWorkingprocedureDeviceReq> devices) {
        List<ItemWorkingprocedureDevice> itemWorkingprocedureDevices = new ArrayList<>();
        for (ItemWorkingprocedureDeviceReq device : devices) {
            String deviceIds = device.getDeviceIds();
            if (!StringUtils.isEmpty(deviceIds)) {
                for (String s : deviceIds.split("\\|")) {
                    ItemWorkingprocedureDevice itemWorkingprocedureDevice = new ItemWorkingprocedureDevice();
                    BeanUtils.copyProperties(device, itemWorkingprocedureDevice);
                    itemWorkingprocedureDevice.setDeviceId(Long.valueOf(s));
                    itemWorkingprocedureDevice.setDeviceName(iDeviceService.getById(Long.valueOf(s)).getDeviceName());
                    itemWorkingprocedureDevices.add(itemWorkingprocedureDevice);
                }
            }
        }
        iItemWorkingprocedureDeviceService.batchSave(itemWorkingprocedureDevices);
        return ok();
    }

    @GetMapping("/{orderId}/{wpId}")
    @ApiOperation(value = "根据工序id和订单id查找设备", notes = "根据工序id和订单id查找设备")
    public ApiResponse<List<ItemWorkingprocedureDevice>> devices(@PathVariable("orderId") long orderId, @PathVariable("wpId") long wpId) {
        return ok(iItemWorkingprocedureDeviceService.findByWorkingprocedureId(wpId, orderId));
    }
}
